﻿using Autofac;
using DoNet.Common.Extensions;
using DoNet.Common.Helpers;
using DoNet.EventBus.Abstractions;
using DoNet.EventBus.Memory;
using DoNet.EventBus.RabbitMQ;
using DoNet.Handlers.Handlers;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DoNet.Extensions.Setups
{
    public static class EventBusSetup
    {
        public static void AddEventBusSetup(this IServiceCollection services, IConfiguration config)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (config.app("EventBus:Enabled").ObjectToBool())
            {
                var subscriptionClientName = config.app("EventBus:SubscriptionClientName").ObjectToString();

                services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
                services.AddTransient<VisitLogIntegrationEventHandler>();
                if (config.app("EventBus:RabbitMQ:Enabled").ObjectToBool())
                {
                    services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
                    {
                        var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
                        var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
                        var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
                        var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();

                        var retryCount = 5;
                        if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:RetryCount")))
                        {
                            retryCount = int.Parse(config.app("EventBus:RabbitMQ:RetryCount"));
                        }
                        return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
                    });

                    services.AddRabbitMQSetup(config);
                }
            }
        }

        public static void ConfigureEventBus(this IApplicationBuilder app, IConfiguration config)
        {
            if (config.app("EventBus:Enabled").ObjectToBool())
            {
                var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
                //eventBus.Subscribe<VisitLogIntegrationEvent, VisitLogIntegrationEventHandler>();
            }
        }
    }
}
